//
//  ToastView.swift
//  CosClub
//
//  Created by 沙睿 on 2020/4/24.
//  Copyright © 2020 ios. All rights reserved.
//

import UIKit
import SnapKit
import MBProgressHUD
public class CustomHUD {
    public static let shared = MBProgressHUD()
    
   public static func show(_ text: String = "", view: UIView? = GlobalTools.getWindow()) {
        let hud = CustomHUD.shared
        hud.label.text = ""
        
        guard let contentView = view else {return}
        guard !contentView.subviews.contains(hud) else {
            return
        }
        contentView.addSubview(hud)
        hud.show(animated: true)
    }
    
   public static func dismiss() {
        let hud = CustomHUD.shared
        hud.hide(animated: true)
    }
    
}


public class ToastView: UIView {
    
    public static let shared = ToastView()
    private let label = UILabel("", color: UIColor.app.white, fontSize: 13)
    
    public var title: String?  = "" {
        didSet {
            label.text = self.title
        }
    }
    public convenience init() {
        self.init(frame:CGRect.zero)
    }
    
    public override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = "#000000".color(alpha: 0.85)
        self.layer.cornerRadius = 8
        self.layer.masksToBounds = true
        
        label.numberOfLines = 0
        addSubview(label)
        label.snp.makeConstraints { (maker) in
            maker.edges.equalToSuperview().inset(UIEdgeInsets(top: 16, left: 20, bottom: 16, right: 20))
            maker.center.equalToSuperview()
            maker.height.greaterThanOrEqualTo(0)
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public static func show(_ text: String? = "", view: UIView? = GlobalTools.getWindow()) {
        
        guard let contetnView = view else {
            return
        }
        if let last = contetnView.subviews.last as? ToastView {
            if last.title == text {
                return
            } else {
                
            }
        }
        let toastView = ToastView()
        contetnView.addSubview(toastView)
        
        toastView.makeLayout(ToastViewLayout(superView: contetnView))
        toastView.alpha = 1
        toastView.title = text
        
        UIView.animate(withDuration: 0.3, delay: 3, options: .curveEaseOut, animations: {
            toastView.alpha = 0
        }) { (_) in
            toastView.removeFromSuperview()
        }
     }
  
    
}

public struct ToastViewLayout : Layoutable {
    public func layoutMaker(inset: Int = 0) -> (ConstraintMaker) -> Void {
         return { maker in
                   maker.center.equalTo(self.superView)

               }
    }
    
    public var superView : UIView
    public init(superView:UIView) {
        self.superView = superView
    }
}
